package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.NavDao;
import com.cn.wanxi.dao.impl.NavImpl;
import com.cn.wanxi.model.NavModel;
import com.cn.wanxi.model.ResultModel;
import com.cn.wanxi.service.NavService;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

public class NavServiceImpl implements NavService {
    @Override
    public ResultModel findAll(NavModel navModel) {
        return null;
    }

    @Override
    public ResultModel updateEnable(NavModel navModel) {
        return null;
    }

    @Override
    public ResultModel updateField(NavModel navModel) {
        return null;
    }

    @Override
    public ResultModel delete(NavModel navModel) {
        return null;
    }

    @Override
    public ResultModel add(NavModel navModel) {
        return null;
    }

    @Override
    public ResultModel findById(NavModel navModel) {
        return null;
    }

    /**
     * 当删除集合时，我们需要删除当前所有的key值
     *
     * @param navModel
     * @return
     */
    @Override
    public ResultModel update(NavModel navModel) {
        NavDao navDao = new NavImpl();
        int update = navDao.update(navModel);
        if (update > 0) {
            Jedis jedis = new Jedis();
            jedis.del("titles", "hrefs");
        }
        return ResultModel.getModel(update);
    }

    @Override
    public ResultModel getCount(NavModel navModel) {
        return null;
    }

    /**
     * 1.判断redis里面是否有数据
     * 2.有，则取redis然后封装成集合
     * 3.没有，则取数据库，然后存入reids
     *
     * @return
     */
    @Override
    public List<NavModel> getNavModelList() {
        List<NavModel> list = new ArrayList<>();
        Jedis jedis = new Jedis();
        Boolean key = jedis.exists("titles");
        if (key) {
//            取得当前key值的list的长度
            int length = Math.toIntExact(jedis.llen("titles"));
            List<String> titles = jedis.lrange("titles", 0, length);
//            以后遇到取集合的时候 start为0，end可以直接写-1；就表示取所有
            List<String> hrefs = jedis.lrange("hrefs", 0, -1);
            for (int i = 0; i < length; i++) {
                NavModel navModel = new NavModel();
                navModel.setTitle(titles.get(i));
                navModel.setHref(hrefs.get(i));
                list.add(navModel);
            }
            System.out.println("redis");
        } else {
            NavDao navDao = new NavImpl();
            list = navDao.getNavModelList();
            for (int i = 0; i < list.size(); i++) {
                jedis.rpush("titles", list.get(i).getTitle());
                jedis.rpush("hrefs", list.get(i).getHref());
            }
            System.out.println("mysql");

        }
        return list;
    }
}
